<?php

namespace web\util;

use Doctrine\Common\Cache\RedisCache;
use EasyWeChat\Foundation\Application;
use common\util\Curl;
use common\util\UrlUtil;
use think\Config;

class WechatUtil {
    const appid = 'wx5f9dc64bb087f4ad';
    
    public static function getPassportUidFromSession(){
        return session(self::getPassportUidKey(self::appid));
    }
    
    public static function getPassportUser(){
        return session(self::getPassportUserKey(self::appid));
    }
    
    private static function getTokenKey(){
        return 'prod_tk';
    }
    
    private static function  getPassportUidKey($appid){
        return 'wx_passport_uid_'.$appid;
    }
    
    private static function  getPassportUserKey($appid){
        return 'wx_passport_user_'.$appid;
    }
    
    public static function getPassportUid() {
        $passportUid = self::getPassportUidFromSession();
        if ($passportUid) {
            return $passportUid;
        }
        
        $tk = cookie(self::getTokenKey());
        if ($tk) {
            
            $tkApiUrl = Config('tk_api_url');
            $url = sprintf($tkApiUrl, $tk);
            $curl = new Curl($url);
            $curl->singleHttpGet();
            if (200 == $curl->getHttpCode()) {
                $res = $curl->getResponse();
                $res = json_decode($res, true);
                if (200 == $res['s']) {
                    $user = $res['data']['user'];
                    session(self::getPassportUidKey(self::appid), $user['id']);
                    session(self::getPassportUserKey(self::appid),$user);
                }
            }
        }
        // 授权
        $url = self::getWeixinAuthUrl(UrlUtil::getCurUrl(),self::appid); 
        header("Location: $url");
        exit();
    }
    
    /**
     * @desc 获取授权链接
     * @param string $appid
     * @param string $url
     */
    public static function getWeixinAuthUrl($url){
        $appid = self::appid;
        $baseAuthApiUrl = Config('auth_api_url');
        return sprintf($baseAuthApiUrl, $appid, urlencode($url));
       
    }
    

    public static function getAcceessToken($appId) {
        $api = "https://pay.mlilife.com/api/get_access_token?app_id=$appId";
        $curl = new Curl($api);
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $curl->singleHttpGet();
        $result = $curl->getResponse();
        return json_decode($result, true)['data']['token'];
    }
    
    private static $_apps = [];
    public static function getAppInfoByAppId($appId = 'wx5f9dc64bb087f4ad') {
        $appids = Config::get('appids');
        return $appids[$appId];
    }
    
    public static function getWechatApp($appId) {
        if (key_exists($appId, self::$_apps)) {
            return self::$_apps[$appId];
        } else {
            $appids = Config::get('appids');
            $appInfo = $appids[$appId];
            
            $config = [
                'app_id' => $appInfo['app_id'],
                'secret' => $appInfo['secret'],
                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                'response_type' => 'array'
            ];
            if(extension_loaded('Redis')){
                $cache = new RedisCache();
                // 创建 redis 实例
                
                $redis = new \Redis();
                $redis->connect('REDIS_HOST', 6379);
                
                $cache->setRedis($redis);
                $config['cache'] = $cache;
            }
            
            $app = new Application($config);
            
            self::$_apps[$appId] = $app;
            return $app;
        }
    }
    
}
